// 投票的公共方法mixin
import { getBindInfo, getVoteDetail, voteAdd } from '@/api/index'
import {objectToParams} from '@/util/function'
import ls from '@/util/ls'
import dayjs from 'dayjs'
import applyforactiviation from '@/static/applyforactiviation.png'

export default {
  data() {
    return {
      isLoading: true,
      scrollTop: 0,
      formData: {
        houseId: '',
        voteSign: '',
        optionId: '',
        voteId: '',
        liveUserId: '',
        communityId: ''
      },
      houseList: [],
      voteInfo: {},
      VotingratioInfo: {},
      optionInfo: {
        zongvoteNum: 0,
        zongvoteSize: 0,
        voteRule: -1 // 2,4为多选 1,3为单选
      },
      pmsVoteOptions: [],
      // pmsVoteOptionMap: {}, // 添加多问题数据结构
      isClick: false,
      votedHouseIds: [],
      isVotingInfo: {
        isVoting: false, // 自己是否投票
        voteId: 0,
        optionId: [],
        houseId: "",
        createDate: "",
        status: 1, // 0投票结束 1投票中 2投票未开始 4没有绑定成功的房子
        voteSign: "",
        voteRule: -1,
        recordId: 0
      },
      options: {},
      nvtoStatus: 0, // 1跳转签名
      houseId: "",
      isFirstPage: false
    }
  },

  watch: {
    formData: {
      handler(newVal) {
        this.updateIsClick()
      },
      deep: true
    }
  },

  computed: {
    isChooseAHouse() {
      let status = this.isVotingInfo.status
      let isVoting = this.isVotingInfo.isVoting
      if (status == 0 && !isVoting) {
        return false
      } else if (status == 2) {
        return false
      }
      return true
    },
    isSignature() {
      let status = this.isVotingInfo.status
      let isVoting = this.isVotingInfo.isVoting
      if (status == 0 && !isVoting) { // 结束了 没有签名的
        return false
      } else if (status == 2) { // 未开始
        return false
      }
      return true
    }
  },

  onLoad(options) {
    this.isLoading = true
    this.options = options

  },

  onShow() {
    if (this.nvtoStatus == 1) {
      this.nvtoStatus = 0
      return
    }
    setTimeout(() => {
      this.init(this.options)
    }, 50)
  },

  onPageScroll(e) {
  
    this.scrollTop = e.scrollTop
  },

  methods: {
    share(){
      let type=this.options.type
      let title=this.voteInfo.voteTitle
    
      let path=""
      let params=objectToParams({
        voteId:this.formData.voteId,
        communityId:this.formData.communityId,
        wxUserId:this.formData.liveUserId,
        type:type
      }) 
      if(type==1){
        path=`/pages/votingForm/index?${params}`
      }else if(type==2){  
        path=`/pages/quickresolution/index?${params}`
      }else if(type==3){
        path=`/pages/questionnaire/index?${params}`
      }else if(type==4){
          path=`/pages/initiative/index?${params}`
        }
      return {
        title,
        path,
       
      }
    },
    // 更新isClick状态 - 子类可以重写此方法
    updateIsClick() {
      let fromdata = this.formData
      if (fromdata.voteSign) {
        this.isClick = true
      } else {
        this.isClick = false
      }
    },

    // 解析scene参数的函数
    parseSceneParams(options) {
      if (options.scene) {
        try {
          // 解码scene参数
          const decodedScene = decodeURIComponent(options.scene)
          
          // 使用原生字符串解析方法替代URLSearchParams
          const params = {}
          const queryString = decodedScene
          const pairs = queryString.split('&')
          
          for (let pair of pairs) {
            const [key, value] = pair.split('=')
            if (key && value) {
              params[key] = value
            }
          }
          
          const voteId = params.voteId
          const communityId = params.communityId
          
          if (voteId) {
            options.voteId = voteId
          }
          if (communityId) {
            options.communityId = communityId
          }
          
          return { voteId, communityId }
        } catch (error) {
          console.error("解析scene参数失败:", error)
        }
      }
    },

    goToSign() {
      this.nvtoStatus = 1
    },

    login() {
      return new Promise((resolve, reject) => {
        let token = ls.get("token")
        if (!token) {
          uni.navigateTo({
            url: "/pages/login/index?login=2"
          })
        }
      })
    },

    handleClick() {
      let fromdata = JSON.parse(JSON.stringify(this.formData))
      fromdata.optionList = this.formData.optionId
      fromdata.optionId = undefined
      fromdata.voteId = Number(fromdata.voteId)
      fromdata.recodeType="1"
      
      if (this.houseList && this.houseList.length > 0) {
        fromdata.houseId = this.houseList[0].houseId
      } else {
        uni.showModal({
          title: "提示",
          content: "您还没有绑定房屋，请先绑定房屋",
          success: () => {
            uni.switchTab({
              url: "/pages/home/index"
            })
          }
        })
        return
      }

      this.formData.houseId = ""
      this.formData.voteSign = ""
      this.formData.optionId = ""
      fromdata.optionList = []
      
      voteAdd(fromdata).then(res => {
        this.methodGetVoteDetail()
      })
    },
    handleVoteAdd(fromdata,type=1){
      fromdata.recordType=1
      voteAdd(fromdata).then(res => {
        if(res.code==200){
         if(type==2){
             this.formData.houseId = ""
            this.formData.voteSign = ""
            this.formData.optionId = ""
         }
          this.methodGetVoteDetail()
          this.showVoteSuccessModal()
        }else{
          uni.showToast({
            title: res.msg,
            icon: "none"
          })
        } 
      })
    },
    getCurrentpage() { // 分享或者扫码打开的
      let pages = getCurrentPages()
      let len = pages.length
      if (len == 1) {
        this.$store.commit("community/setCommunityId", this.formData.communityId)
      }
      this.isFirstPage = (len === 1)
    },

    async init(options) {
      if (options.scene) { // 分享进来的  // 处理scene参数，如果存在则解析其中的voteId和communityId
        options = this.parseSceneParams(options)
      }
      
      let token = ls.get("token")
      let user = this.$store.state.app.user
      if (user && user.wxUser) {
        options["wxUserId"] = user.wxUser.wxUserId
      }
      if (!token) {
        await this.login()
        let t = setTimeout(() => {
          this.setParams(options)
          clearTimeout(t)
        }, 1000)
      } else {
        this.setParams(options)
      }
    },

    async setParams(options) {
      this.formData.voteId = options.voteId
      this.formData.liveUserId = options.wxUserId
      this.formData.communityId = options.communityId
      
      this.$nextTick(() => {
        this.getVoteList()
        this.methodGetVoteDetail()
        this.getCurrentpage()
      })
    },

    async getVoteList() {
      let data2 = await getBindInfo({
        communityId: this.formData.communityId,
        wxUserId: this.formData.liveUserId,
        auditStatus: 2
      })
      this.$store.commit("community/setBoundHouses", data2.rows.length)
    },

    selectHouse(house) {
      try {
        this.isVotingInfo.houseId = house.id
        this.houseId = house.id
        
        this.verifyHouse(house.id)
        this.formData.houseId = house.id
      } catch (error) {
        console.error('选择房屋失败:', error)
      }
    },

    verifyHouse(houseId) {
      let row = this.votedHouseIds.find(item => item.houseId == houseId)
      
      if (row) {
        this.setIsVotingInfo(row)
      } else {
        this.isVotingInfo = {
          isVoting: false,
          voteId: 0,
          optionId: [],
          houseId: 0,
          createDate: "",
          status: 1,
          voteSign: ""
        }
        // 子类可以重写此方法来自定义选项处理逻辑
        this.handleOptionSelection()
      }
    },

    // 处理选项选择 - 子类可以重写此方法
    handleOptionSelection() {
      if (this.$refs.voteFrom && this.$refs.voteFrom.getSelectedIndex) {
        let indx = this.$refs.voteFrom.getSelectedIndex()
        if (indx.length >= 0) {
          this.formData.optionId = indx
        }
      }
    },

    setIsVotingInfo(row) {

      this.isVotingInfo.recordId = row.recordId
      
      let voteOptionIds = JSON.parse(row.voteOptionId)
      if (voteOptionIds.length == 1) {
        this.isVotingInfo.optionId = JSON.parse(row.voteOptionId)[0]
      } else {
        this.isVotingInfo.optionId = JSON.parse(row.voteOptionId).map(e => Number(e))
      }
      this.isVotingInfo.isVoting = true
      this.isVotingInfo.voteId = row.voteId
      this.isVotingInfo.houseId = row.houseId
      this.isVotingInfo.createDate = row.createDate
      this.isVotingInfo.voteSign = row.voteSign
    },

    uploadSign(res) {
      this.formData.voteSign = res
    },

    handleTime(startDate, endDate) {
      let now = dayjs()
      let start = dayjs(startDate)
      let end = dayjs(endDate)
      
      let status = 0
      if (now.isBefore(start)) {
        status = 2 // 未开始
      } else if (now.isAfter(end)) {
        status = 0 // 已结束
      } else {
        status = 1 // 进行中
      }
      return status
    },

    async methodGetVoteDetail() {
      let datas = await getVoteDetail({
        voteId: this.formData.voteId.toString(),
        userId: this.formData.liveUserId,
        communityId: this.formData.communityId.toString()
      })
      let data = datas.data
      
      try {
        let pmsVoteRecords = data.pmsVoteRecords
        console.log("pmsVoteRecords",pmsVoteRecords)
        let pmsVote = data.pmsVote
        
        // 初始化已投票房屋id数组
        this.votedHouseIds = (pmsVoteRecords || [])
        
        this.isVotingInfo.status = this.handleTime(pmsVote.startDate, pmsVote.endDate)
        this.isLoading = false
        
        if (pmsVoteRecords && pmsVoteRecords.length > 0) {
          let houseId = this.houseId
          let pmsVoteRecordszero = null
          
          if (houseId !== "") {
            pmsVoteRecordszero = pmsVoteRecords.find(item => item.houseId == houseId)
          } else {
            pmsVoteRecordszero = pmsVoteRecords[0]
          }
          console.log("pmsVoteRecordszero",pmsVoteRecordszero)
          if(pmsVoteRecordszero){
            this.setIsVotingInfo(pmsVoteRecordszero)
          }
        
        } else {
          this.isVotingInfo.isVoting = false
          this.isVotingInfo.houseId = ''
        }
        
        this.voteInfo = data.pmsVote
        
        let sumVoteTotalPerson = data.sumVoteTotalPerson || 0
        let sumTotalSize = data.sumTotalSize || 0
        let sumVoteTotalSize = data.sumVoteTotalSize || 0
        // sumTotalPerson 总人数   sumVoteTotalPerson 投票总人数  
        // sumTotalSize 总面积  sumVoteTotalSize 投票总面积
        console.log("sumVoteTotalPerson",sumVoteTotalPerson,data.sumTotalPerson,((sumVoteTotalPerson / data.sumTotalPerson)*100).toFixed(2))
        this.VotingratioInfo = {
          already: data.sumVoteTotalPerson || 0,
          alreadyproportion: ((sumVoteTotalPerson / data.sumTotalPerson)*100).toFixed(2) + "%",
          personproportion: ((  sumVoteTotalSize/ sumTotalSize)*100).toFixed(2) + "%",
          sumTotalSize:sumTotalSize,
          sumVoteTotalSize: sumVoteTotalSize || 0,
          sumTotalPerson: data.sumTotalPerson,
        }
        
        let pmsVoteOptions = data.pmsVoteOptions
        this.pmsVoteOptions = pmsVoteOptions
        
        let zongvoteNum = pmsVoteOptions.reduce((total, item) => total + item.voteNum, 0)
        let zongvoteSize = pmsVoteOptions.reduce((total, item) => total + item.areaNum, 0)
        
        this.optionInfo = {
          zongvoteNum,
          zongvoteSize,
          voteRule: pmsVote.voteRule
        }
        
        this.houseList = data.pmsHouses 
       if(!this.houseList){  //如果没有审核成功的房子
        this.isVotingInfo.status=4
       }
        
        // 子类可以重写此方法来处理额外的数据
        this.handleAdditionalData(data)
        
      } catch (error) {
        console.log("error",error)
        uni.showModal({
          title: "提示",
          content: "该投票已经结束，请返回首页",
          success: () => {
            uni.switchTab({
              url: "/pages/home/index"
            })
          }
        })
      }
    },

    // 处理额外数据 - 子类可以重写此方法
    handleAdditionalData(data) {
      // 默认实现为空，子类可以重写
    },

        // 投票成功弹框
    showVoteSuccessModal() {
      // 使用 uView Modal 组件显示投票成功弹框
      this.$refs.voteSuccessModal && this.$refs.voteSuccessModal.showModal()
    },

    // 显示投票成功弹框（内部方法）
    showModal() {
      if (this.$refs.voteSuccessModal) {
        this.$refs.voteSuccessModal.show = true
      }
    },

    // 投票成功确认后的处理 - 子类可以重写此方法
  
  }
} 